/*本模块功能:机构管理专业管理(管理员)
        编写者:朱光曜
        编写时间:2017.11.03*/
$(function() {
	var string1 = '<tr>' +
		'<th class="col-lg-2"><input type="checkbox" name="controlAll" id="controlAll" class="allCheck"></th>' +
		'<th class="col-lg-9">专业</th>' +
		'<th class="col-lg-3">操作</th>' +
		'</tr>';
	/*列表头*/
	var confirm1 = new Confirm;
	var set = new Confirm;
	var Alert1 = new Alert;
	var Alert2 = new Alert;

	function tabelModel(data) {
    /*列表内容*/
		return '<tr data-num="0">' +
			'<td class="col-lg-2"><input value="0" name="selecteds" type="checkbox" class="oneCheck"  professionId="' + data.professionList[key].professionId + '"/></td>' +
			'<td class="col-lg-10"  title="' + data.professionList[key].professionName + '">' + data.professionList[key].professionName + '</td>' +
			'<td class="col-lg-3">' +
			'<a href="javascript:;" class="setMajor">修改专业</a>' +
			'<a class="setLocation" href="javascript:;">修改地点</a>' +
			'</td>' +
			'</tr>';

	};

	function unit() { //拖拽插件代码
		var updateOutput = function(e)

		{

			var list = e.length ? e : $(e.target),

				output = list.data('output');

			if(window.JSON) {

				output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2));

			} else {

				output.val('JSON browser support required for this demo.');

			}

		};

		$('#nestable').nestable({

				group: 1

			})

			.on('change', updateOutput);

		$('#nestable2').nestable({

				group: 1

			})

			.on('change', updateOutput);

		updateOutput($('#nestable').data('output', $('#nestable-output')));

		updateOutput($('#nestable2').data('output', $('#nestable2-output')));
		setInterval(function() {
			$("button").off("click").click(function() {
				var actions = $(this).attr("data-action");
				if(actions == "collapse") {
					$(this).hide().siblings("button").show();
					$(this).siblings("ol").hide();
				}
				if(actions == "expand") {
					$(this).hide().siblings("button").show();
					$(this).siblings("ol").show();
				}

			});
		}, 100);
	};

	function directionLocation(data) {
		/*拖拽地点*/
		var nestable = "";
		for(key in data.allSiteList) {
			nestable += '<li class="dd-item" data-id="' + key + '" siteId="' + data.allSiteList[key].siteId + '">' +
				'<div class="dd-handle">' + data.allSiteList[key].siteName + '</div>' +
				'</li>';
		}
		var nestable2 = "";
		for(key in data.mySiteList) {
			nestable2 += '<li class="dd-item" data-id="' + key + '" siteId="' + data.mySiteList[key].siteId + '">' +
				'<div class="dd-handle">' + data.mySiteList[key].siteName + '</div>' +
				'</li>';
		}
		return '<div class="directionLocation"><!--地点-->' +
			'<div style="height: 40px;" class="prompt">' +
            '<span style="font-size: 14px;" class="fl">提示 :&ensp;</span>' +
            '<ul style="color: #949494;line-height: 22px;" class="fl">' +
            '<li>请将想选择的地点由‘所选教学地点’拖动至‘已选教学地点’。</li>' +
            '</ul>' +
            '</div>'+
			'<div class="left fl">' +
			'<p>所有教学地点</p>' +
			'<div class="dd" id="nestable">' +
			'<ol class="dd-list">' +
			nestable +
			'</ol>' +
			'</div>' +
			'</div>' +
			'<div class="rotate fl"><img src="pc/images/log_locationZ.png" alt="旋转图标" /></div>' +
			'<div class="right fr">' +
			'<p>已选教学地点</p>' +
			'<div class="dd" id="nestable2">' +
			'<ol class="dd-list">' +
			nestable2 +
			'</ol>' +
			'</div>' +
			'</div>' +
			'<div class="clear">' +
			'</div>' +
			'</div>';
	};

	function revisionMajorMethod(data) {
		/*添加专业*/
		var direction = "";
		for(key in data.directList) {
			direction += '<div class="inputRight" mainId="' + data.directList[key].mainId + '"><label for="departName">专业方向:&ensp;</label><input autocomplete="off type="text"  maxlength="20" class="publicText majorDirection" placeholder="请输入专业方向" value="' + data.directList[key].directName + '"/><img src="pc/images/log_reduce.png" alt="减" class="reduce" /></div>';
		}
		return '<div class="inputRight" professionId="' + data.profession.professionId + '" departmentId="' + data.profession.departmentId + '"><label for="departName">专业名称:&ensp;</label><input autocomplete="off type="text" id="major" maxlength="20" class="publicText" placeholder="请输入专业名称" value="' + data.profession.professionName + '" /></div>' +
			'<div class="professionalDirection"><!--专业-->' +
			'<div>' +
			direction +
			
			'</div>' +
			'<img src="pc/images/log_plus.png" alt="加"  class="plus"/>' +
			
			'</div>';
	};
	var loading1 = new Loading();//监控全局ajax添加loading
	loading1.init();
    $(document).ajaxSend(function(){
		loading1.show();
		
		});
	$(document).ajaxStop(function(){
		loading1.hide();
		
		});
	var nowData = 1;
	var index = {
		init: function() {
			this.bind();
		},
		bind: function() {
			var self = this;
			this.data_content = {}; //搜索集
			this.tab_content = {}; //列表集
		
			this.parameter = {
				"pageNow": 1,
				"pageSize": 10,
				"departmentId":result.paramData.departmentId
			};
           
			this.postData(this.parameter, nowData);

			$(".deleteMajor").off("click").on("click", function() {
				self.delListEvent();
			});
			$(".addMajor").off("click").click(function() { //添加专业
				var json = JSON.stringify({
					"pageName": "adminAddProfessionalDetails",
					"paramData": {
						/*"classId": $(this).parents("tr").attr("classId"),
						"courseId": $(this).parents("tr").attr("courseId"),
						"stuorteaId": $(this).parents("tr").attr("stuorteaId"),*/
						"departmentId":result.paramData.departmentId
					}
				});
				window.location.href = "skipPage?jsonStr=" + json;
				//$("#ifMain,parent.document").attr("src","skipPage?jsonStr=" + json);
			});

		},

		postData: function(par_data, nowData, hunt) { //获得搜索及列表数据
			var self = this;
			var parameter = par_data;
          
			$.ajax({
				type: "post",
				url: "skipDepProfessionMana",
				async: true,
				data: {
					"jsonStr": JSON.stringify(parameter)
				},
				success: function(data, status, xhr) {
					var new_data = JSON.parse(data);
                    if(new_data.result == "success"){
                        if(hunt) {
                            self.tab_content = new_data;

                            self.tab_add();
                        } else {

                            self.data_content = new_data;
                            self.tab_content = new_data;

                            self.add();
                            self.tab_add();
                        }

                        var sumpage = new_data.totalPage;
                        if(sumpage<1){sumpage=1;};
                        var nowpage = 1;
                        var pagenumber = 10;
                        var parame = parameter;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {

                                nowpage = p;

                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                if(!parameter) {
                                    parameter = {
                                        "pageNow": nowpage,
                                        "pageSize": 10
                                    };

                                } else {
                                    parameter.pageNow = nowpage;

                                }
                                $.ajax({
                                    type: "post",
                                    url: "skipDepProfessionMana",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        //获取院系
                                        var msgNew = JSON.parse(msg);
                                        self.tab_content = msgNew;

                                        self.tab_add();
                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
					}else{
                        if(new_data.failMsg == "暂无权限"){
                            parent.location.reload(true);
                        }
					}

				},
				error: function(data, status, xhr) {
				
					var json = JSON.stringify({
						"pageName": "error"
				    });
					window.location.href = "skipPage?jsonStr=" + json;
				}
			});
		},
		add: function() { //搜索追加
			var self = this;
			var data = self.data_content;
			
			if(data.departmentMsg!==null){
				$(".funBox .department").html(data.departmentMsg.departmentName + ".");
			}
			

		},
		tab_add: function() { //列表追加

			var self = this;
			var data = self.tab_content;
			var table = string1;

			//data.selectList={};

			var i = 0;
			for(key in data.professionList) {
				i++;
			}

			if(i > 0) {

				for(key in data.professionList) {

					table += tabelModel(data);
				}

				$(".mainContent .tableBox").html(table);
                maxLengthLimit.init("publicText");
			} else {
				var trImg = "<tr><td colspan='3'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td/tr>";
				$(".mainContent .tableBox").html(string1 + trImg);
			}
			//设置列表宽度(最大为9)
			var numMax = 0;
			$(".tableBox tr th").each(function() {
				var str = $(this).attr("class");
				var num = str.lastIndexOf("col-lg-") + 7;
				var num1 = parseFloat(str.substring(num, num + 1));
				numMax += num1;
			});

			$(".tableBox tr th").each(function() {
				var str = $(this).attr("class");
				var num = str.lastIndexOf("col-lg-") + 7;
				var num1 = parseFloat(str.substring(num, num + 1));
				
				$(this).css("width", num1 / numMax * 100 + "%");
			});
			self.allCheckEvent();
			$(".setMajor").off("click").click(function() { //修改专业
				var $_self = self;
				var professionId = $(this).parents("tr").children("td").eq(0).children("input").attr("professionid");
				var parameters = {
					"professionId": professionId
				};

				$.ajax({
					type: "post",
					url: "skipSaveProfession",
					async: true,
					data: {
						"jsonStr": JSON.stringify(parameters)
					},

					success: function(data) {
						var $self = $_self;
						var msgNew = JSON.parse(data);
						var con = revisionMajorMethod(msgNew);

						var _method = function() {

							var self = $self;
							var professionName = $("#major").val();
							var directions = [];
							var sites = [];
							var professionId =parseInt( $("#set .alert_content .inputRight").attr("professionid"));
							var directions = [];
							var delList=[];
							var index = 0;
							var bool = false;
							$(".majorDirection").each(function() {
								
								//if($(this).val() !== "") {
									//console.log(parseInt($(this).parents(".inputRightDel").attr("mainId")));
									
									if(verification.specialCode($(this).val()) !== true) {
										self.alert1("不能输入特殊字符(@/'\"#$%&^*)","majorFail");
										bool = true;
										return;

									} else if($(this).val()=="") {
										
										if($(this).parents(".inputRight").attr("mainId")!=="0"){
											
										if($(this).parents(".inputRightDel").attr("mainId")!=="0"){
										delList.push(parseInt($(this).parents(".inputRightDel").attr("mainId")));
										};
										};
										return true;

									} else{
										directions[index] = {
											"directName": $(this).val(),
											"mainId": parseInt($(this).parents(".inputRight").attr("mainId"))
										};
									}
									index++;
								//}
								
							});
							$(".inputRight .majorDirection").each(function(){
								if($(this).val()=="") {
									self.alert1("专业方向不能为空","majorFail");
									bool = true;
									return;

								} 
							});
							if(bool) {
								return;
							}
							var locationParameters = {
								"professionName": professionName,
								"professionId": professionId,
								"directions": directions,
								"delList":delList
							};
							
						
							
							if(professionName == "") {
								self.alert1("请输入专业名称","majorFail");
							} else if(verification.specialCode(professionName) !== true) {
								self.alert1("不能输入特殊字符(@/'\"#$%&^*)","majorFail");
							} else if(directions.length == 0) {
								self.alert1("请输入专业方向","majorFail");
							} else {
								$.ajax({
									type: "post",
									url: "saveProfession",
									async: true,
									data: {
										"jsonStr": JSON.stringify(locationParameters)
									},

									success: function(msg) {

										var msgNew = JSON.parse(msg);

										if(msgNew.result == "success") {
											self.alert1("修改成功");
										} else {
											if(msgNew.failMsg){
												self.alert1(msgNew.failMsg,"majorFail");
											}else{
												self.alert1("修改失败");
											}
											
										}

									},
									error: function(data, status, xhr) {
										var json = JSON.stringify({
											"pageName": "error"
									    });
										window.location.href = "skipPage?jsonStr=" + json;

									}
								});
							}
							$(".alert").removeAttr("id");
						};

						$_self.setInit("修改专业", con, _method);

					},
					error: function(data, status, xhr) {
						var json = JSON.stringify({
							"pageName": "error"
					    });
						window.location.href = "skipPage?jsonStr=" + json;

					}
				});
                
				

			});
			
			//$(document).off("click").on("click", ".professionalDirection .plus", function() { //点击添加方向
				
				
				/**/

			//});
		
			$(document).off("click", ".professionalDirection .reduce").on("click", ".professionalDirection .reduce", function() { //点击删除方向
				
				if($(".professionalDirection>div  .inputRight").length > 1){
				if($(this).parents(".inputRight").attr("mainId")=="0"){
				
					$(this).parents(".inputRight").remove();
				}else{
					var myClick=$(this);
					if($(this).parents(".inputRight").attr("mainId")=="0"){$(this).parents(".inputRight").remove();return;}
					var delProfessDirectionParameters={
							"mainId":parseInt($(this).parents(".inputRight").attr("mainId"))
					};
					$.ajax({
						type: "post",
						url: "delProfessDirection",
						async: true,
						data: {
							"jsonStr": JSON.stringify(delProfessDirectionParameters)
						},

						success: function(msg) {
                          
							var msgNew = JSON.parse(msg);
							
							if(msgNew.result == "success") {
								
								if(msgNew.delMark==0){
									myClick.parents(".inputRight").css("display","none").removeClass("inputRight").addClass("inputRightDel");
									myClick.siblings(".majorDirection").val("");
								}else{
									set.hide();
									self.alert1(msgNew.delMsg,"majorFail");
								}
							} else {
								//set.hide();
								
									//self.alert1("删除失败","majorFail");
								if(msgNew.failMsg){
									self.alert1(msgNew.failMsg,"majorFail");
								}else{
									self.alert1("删除失败","majorFail");
								}

								
							}

						},
						error: function(data, status, xhr) {
							var json = JSON.stringify({
								"pageName": "error"
						    });
							window.location.href = "skipPage?jsonStr=" + json;

						}
					});
				}
				}
			});
			$(".setLocation").off("click").click(function() { //修改地点
				var $_self = self;
				var professionId = $(this).parents("tr").children("td").eq(0).children("input").attr("professionid");
				var parameters = {
					"professionId": professionId
				};

				$.ajax({
					type: "post",
					url: "skipSaveProfession",
					async: true,
					data: {
						"jsonStr": JSON.stringify(parameters)
					},

					success: function(data) {
						var $self = $_self;
						var msgNew = JSON.parse(data);
						var con = directionLocation(msgNew);
						var proId = professionId;
						var _method = function() {

							var self = $self;

							var professionId = proId;
							var sites = [];

							$("#nestable2 ol li").each(function() {
								if($(this).val() !== "") {
									sites.push($(this).attr("siteid"));
								}

							});
							var locationParameters = {

								"professionId": professionId,
								"sites": sites
							};
							
							if(sites.length == 0) {
								self.alert1("请选择地点","locationFail");
							} else {
								$.ajax({
									type: "post",
									url: "addProfessionReSite",
									async: true,
									data: {
										"jsonStr": JSON.stringify(locationParameters)
									},

									success: function(msg) {

										var msgNew = JSON.parse(msg);

										if(msgNew.result == "success") {
											self.alert1("修改成功");
										} else {
											//self.alert1("修改失败");
											if(msgNew.failMsg){
												self.alert1(msgNew.failMsg);
											}else{
												self.alert1("修改失败");
											}

										}

									},
									error: function(data, status, xhr) {
										var json = JSON.stringify({
											"pageName": "error"
									    });
										window.location.href = "skipPage?jsonStr=" + json;

									}
								});
							}
							$("#set  .alert_box").width("532px");
							$(".alert").removeAttr("id");
						};

						$_self.setInit("修改地点", con, _method);
						$("#set  .alert_box").width("742px");
						unit(); //插件代码
					},
					error: function(data, status, xhr) {
						var json = JSON.stringify({
							"pageName": "error"
					    });
						window.location.href = "skipPage?jsonStr=" + json;

					}
				});
			});
		},
		setInit: function(conHead, con, math) {//修改专业弹窗
			set.contenthead = conHead;
			set.content = con;
			set.success = math;
			set.fail = function() {
				$("#set  .alert_box").width("532px");
				$(".alert").removeAttr("id");
			};
			set.init();
			$(".alert").attr("id", "set");
			set.show();
            $(".professionalDirection .plus").off("click").click(function(){
            	var $_self = $(this);
				var condition = true;
                console.log("pass");
				
				var num = 0;
				
				
				if($(".professionalDirection .inputRight:last input").val() !== "" ) {
					$(".professionalDirection>div").append('<div class="inputRight"  mainId="0"><label for="departName">专业方向:&ensp;</label><input type="text" maxlength="20" class="publicText majorDirection" placeholder="请输入专业方向"/><img src="pc/images/log_reduce.png" alt="减" class="reduce" /></div>');
					$(".professionalDirection>div").scrollTop($(".professionalDirection>div").height() * 99999);//至底部
					maxLengthLimit.init("publicText");
				}
            });
		},
		alert1: function(content1,state) { //confirm提示

			Alert1.contenthead = "提示";
			Alert1.content = content1;

			Alert1.success = function() {
				if(state=="majorFail"){
					$(".alert").attr("id", "set");
					set.show();
				}else if(state=="locationFail"){
					$(".alert").attr("id", "set");
					$("#set  .alert_box").width("742px");
					
					set.show();
				}else{
					window.location.reload();
				}
				
				Alert1.hide();
			};

			Alert1.init();
			Alert1.show();
		},
		allCheckEvent: function() {
			//全选
			allCheck.init("controlAll", "oneCheck");
		},
		delListEvent: function() { //批量删除
			var $_self = this;
			if($(".oneCheck[value=1]").length == 0) {
				Alert1.contenthead = "提示";
				Alert1.content = "请选择要删除的专业";
				Alert1.success = function() {};
				Alert1.init();
				Alert1.show();
			} else {

				confirm1.success = function() {
					var list = [];
					$(".box_1 tr td .oneCheck").each(function() {
						if(parseInt($(this).val()) == 1) {
							list.push($(this).attr("professionId"));

						}

					});
					
					var deleteDepartmentparameters = list;

					var self = $_self;
					$.ajax({
						type: "post",
						url: "delProfessions",
						async: true,
						data: {
							"jsonStr": JSON.stringify(deleteDepartmentparameters)
						},

						success: function(msg) {

							var msgNew = JSON.parse(msg);

							if(msgNew.result == "success") {
								self.alert1("删除成功");
							} else {
								//self.alert1( msgNew.failMsg);
								if(msgNew.failMsg){
									self.alert1(msgNew.failMsg);
								}else{
									self.alert1("删除失败");
								}

							}

						},
						error: function(data, status, xhr) {
							var json = JSON.stringify({
								"pageName": "error"
						    });
							window.location.href = "skipPage?jsonStr=" + json;

						}
					});
				};
				var num = 0;
				$(".box_1 tr td .oneCheck").each(function() {
					if(parseInt($(this).val()) == 1) {
						num++;
					}

				});
				if(num < 2) {
					confirm1.content = "确定删除这个专业吗";
				} else {
					confirm1.content = "确定删除这<a href='javascript:void(0)'>" + num + "</a>个专业吗";
				}

				confirm1.init();
				$(".alert_content a").css({
					"margin": "2px",
					"color": "#c82011",
					"text-decoration": "underline"
				});
				confirm1.show();

			}
		}

	};
	index.init();

});